package com.mycom.controller;

import com.mycom.controller.constant.Code;
import com.mycom.controller.entity.Result;
import com.mycom.pojo.User;
import com.mycom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping
    public Result save(@RequestBody User user) {
        boolean flag = userService.save(user);
        return new Result(flag ? Code.SAVE_SUCCESS:Code.SAVE_ERR,flag);
    }
    @PutMapping
    public Result update(@RequestBody User user) {
        boolean flag = userService.update(user);
        return new Result(flag?Code.UPDATE_SUCCESS:Code.UPDATE_ERR,flag);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = userService.delete(id);
        return new Result(flag?Code.DELETE_SUCCESS:Code.DELETE_ERR,flag);
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        Integer code = user!=null ? Code.QUERY_SUCCESS:Code.QUERY_ERR;
        String msg = user!=null ? "根据id查询成功！" : "根据id查询失败！";
        return new Result(code,user,msg);
    }
    @GetMapping
    public Result selectAll() {
        List<User> users = userService.selectAll();
        Integer code = users!=null ? Code.QUERY_ALL_SUCCESS:Code.QUERY_ALL_ERR;
        String msg = users!=null ? "查询所有成功！":"查询所有失败！";
        return new Result(code,users,msg);
    }
}
